package eu.jba.denshijisho.util;

import java.util.Date;
import java.util.List;

import android.content.Context;
import eu.jba.denshijisho.R;
import eu.jba.denshijisho.dao.CardDao;
import eu.jba.denshijisho.dao.ConfigurationDao;
import eu.jba.denshijisho.dao.StatDao;
import eu.jba.denshijisho.entity.Card;

public class DataProviderImpl implements DataProvider{

	private Context context;
	
	public DataProviderImpl(Context context){
		this.context = context;
	}
	
	@Override
	public List<Card> provideData() {
		final StringBuilder sb = new StringBuilder();
		sb.append( "select * from " ).append( context.getString( R.database.CARD_TABLE ) ).append(" a,")
		  .append(context.getString( R.database.STAT_TABLE )).append(" b").append(" where a.").append(CardDao.KEY_STAT_ID)
		  .append(" = b.").append( StatDao.KEY_ROWID ).append( " and ").append("date(nextDate) <= date('")
		  .append( Util.dateToString( new Date() ) ).append( "')").append(" limit ").append( getLimit() ).append(";");
		
		final CardDao cardDao = new CardDao( context );
		cardDao.open();
		final List<Card> cards = cardDao.runRawQuery( sb.toString() );
		cardDao.close();
		return cards;
	}

	private int getLimit(){
		final ConfigurationDao configurationDao = new ConfigurationDao( context );
		configurationDao.open();
		int i = configurationDao.get( 1 ).getIntegerValue();
		configurationDao.close();
		return i;
	}
	
	@Override
	public void writeData(List<Card> cards) {
		final StatDao statDao = new StatDao( context );
		statDao.open();
		for( Card card : cards){
			statDao.update( card.getStat() );
		}
		statDao.close();
	}
}
